package com.lovo.psc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lovo.dto.SupplierDto;
import com.lovo.psc.entity.UserBean;
import com.lovo.psc.mapper.IUserMapper;
import com.lovo.psc.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.util.MQUtil;
import com.lovo.util.PscToKen;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 刘英旭
 * @since 2022-07-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<IUserMapper, UserBean> implements IUserService {
    @Autowired
    private IUserMapper IUserMapper;
    //交换机
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public String register(String user, String pwd, String supplierName, String img, String type) {
        int i = this.verifyUser(user);
        if (i != 0) {
            return "账号重复";
        }
        UserBean userBean = new UserBean(user, pwd, supplierName, img, type);
        super.save(userBean);
        SupplierDto supplierDto = new SupplierDto();
        supplierDto.setCommoduser(user);
        supplierDto.setPwd(pwd);
        supplierDto.setName(supplierName);
        supplierDto.setImg(img);
        supplierDto.setClasses(type);
        supplierDto.setCommoduser(userBean.getCommoduser());
        //MQ投送数据
        rabbitTemplate.convertAndSend(MQUtil.DIRECTEXCHANGEREQUEST,MQUtil.REQUESTKEY,supplierDto);
        return "ok";
    }

    @Override
    public String login(String user, String pwd) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("commoduser",user);
        qw.eq("pwd",pwd);
        UserBean one = super.getOne(qw);
        if (one == null){
            return "账号或密码错误";
        }
        if ("1".equals(one.getState())){
            //Token 加密
            return PscToKen.createToken(one);
        }
        if ("0".equals(one.getState())){
            return "审核中";
        }
        //删除账号
        QueryWrapper q = new QueryWrapper();
        q.eq("commoduser",user);
        super.remove(q);
        //审核不通过原因
        return one.getState();

    }

    @Override
    public int verifyUser(String user) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("commoduser", user);
        UserBean one = super.getOne(qw);
        if (one != null) {
            return 1;
        }
        return 0;
    }


    @Override
    public void upDataSupplierState(String supplierNumber, String info) {
        UpdateWrapper uw = new UpdateWrapper();
        uw.eq("number",supplierNumber);
        uw.set("state",info);
        super.update(uw);
    }
}
